package com.cwt_taxi_xa;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.cwt_taxi_xa.constants.MyStatus;
import com.cwt_taxi_xa.protocol.DDUtil;
import com.cwt_taxi_xa.protocol.MCUUtil;
import com.cwt_taxi_xa.protocol.MeterEncoder;
import com.cwt_taxi_xa.receiver.SerialDataReceived;
import com.cwt_taxi_xa.service.SerialPortService;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.GPIOUtil;
import com.cwt_taxi_xa.util.VolumeControl;

public class ActivityPower extends CWTBaseActivity{

	public static boolean isview = false;

	public static long jjqtime = 0;
	public static long ddtime = 0;

	public static boolean chemen = true;

	ListView lv;
	ImageView iv;

	public static boolean sleep = false;

	//	ProgressDialog pd;
	ProgressDialog pd_net;

	String[] data = {
			"主电源状态： 正常",
			"主电源电压： 12V",
			"外部亮度： --",
			"计价器状态： --",
			"评价器状态： --",
			"录像机状态： --",
			"顶灯状态： --",
			"车门状态： --",
			"IO状态： --",
			"GPS天线： --"
	};
	ArrayAdapter<String> adapter;

	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what==1001){//电压
				double dy = Integer.parseInt(((String)msg.obj), 16)+40;//加40是因为测试机个体异常------------------------------------
				data[1] = "主电源电压： "+(dy/100)+"V";

				if(dy>=1800){
					data[0] = "主电源状态： 电压过高";
				}else if(dy<1800&&dy>1000){
					data[0] = "主电源状态： 正常";
				}else{
					data[0] = "主电源状态： 电压过低";
				}


				int pj3 = GPIOUtil.readIOState("/proc/input3");
				int pj5 = GPIOUtil.readIOState("/proc/input5");
				int pj6 = GPIOUtil.readIOState("/proc/input6");
				int bj = GPIOUtil.readIOState("/proc/detect_warning");
				if(!(pj3==1&&pj5==1&&pj6==1)){
					data[4] = (data[4].split("： ")[0])+"： 正常 (状态："+pj3+","+pj5+","+pj6+")"+"  (报警状态："+(bj==0?"按下)":"松开)");
				}else{
					data[4] = (data[4].split("： ")[0])+"： 断开 (状态："+pj3+","+pj5+","+pj6+")"+"  (报警状态："+(bj==0?"按下)":"松开)");
				}



				data[2] = "外部亮度： "+MCUUtil.light;
				data[8] = "IO状态： "+MCUUtil.stats;
				data[9] = "GPS天线： "+SerialDataReceived.gpsstatus;
				if(adapter==null){
					adapter = new ArrayAdapter<String>(ActivityPower.this, android.R.layout.simple_list_item_1, data);
					lv.setAdapter(adapter);
				}
				adapter.notifyDataSetChanged();
			}
			if(msg.what==1002){
				if(adapter==null){
					adapter = new ArrayAdapter<String>(ActivityPower.this, android.R.layout.simple_list_item_1, data);
					lv.setAdapter(adapter);
				}

				adapter.notifyDataSetChanged();
			}
			if(msg.what==1004){
				int index = (int) msg.obj;
				index++;
				if(index<data.length){
					check(index);
				}else{
					checknet();
//					if(pd!=null){
//						try {
//							pd.dismiss();
//							checknet();
//						} catch (Exception e) {
//							// TODO: handle exception
//						}
//					}
				}
			}
			if(msg.what==1005){
				if(pd_net!=null){
					try {
						pd_net.dismiss();
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
				if(MyStatus.online){
					Toast.makeText(ActivityPower.this, "网络已连接", 1500).show();
					if(sleep){
						sleep = false;
						finish();
					}
				}else{
					Toast.makeText(ActivityPower.this, "网络未连接", 1500).show();
				}
			}

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_aa_power);
		lv = (ListView) findViewById(R.id.listView1);
		iv = (ImageView) findViewById(R.id.imageView1);

		iv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				check(3);
			}
		});


	}

	protected void checknet() {
		try {
			if(pd_net==null){
				pd_net = ProgressDialog.show(ActivityPower.this, "请稍等",
						"正在等待网络连接");
			}else{
				pd_net.show();
			}
		} catch (Exception e) {
		}
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(1000);
					for (int i = 0; i < 100; i++) {
						if(MyStatus.online){
							break;
						}else{
							Thread.sleep(1000);
						}
					}
					handler.sendEmptyMessage(1005);
				} catch (Exception e) {
				}
			}
		}).start();
	}

	void check(final int index){
//		if (pd == null) {
//			pd = ProgressDialog.show(ActivityPower.this, "请稍等",
//					"正在自检");
//		} else {
//			pd.show();
//		}
		new Thread(new Runnable() {

			@Override
			public void run() {
				data[index] = (data[index].split("： ")[0])+"： 检查中";
				handler.sendMessage(handler.obtainMessage(1002));

				boolean c = false;
				switch (index) {
					case 3:
						try {
							for (int i = 0; i < 5; i++) {
								if(SerialPortService.getInstance()==null){
									Thread.sleep(1000);
								}else{
									break;
								}
							}
						} catch (Exception e) {
							// TODO: handle exception
						}
						try {SerialPortService.getInstance().sendSerialData6(MeterEncoder.queryMeterState());} catch (Exception e) {}

						try {Thread.sleep(2000);} catch (Exception e) {}
						c = System.currentTimeMillis()-jjqtime<2000;
						if(!c){
							MCUUtil.reH = false;

//						TTsFunction.speakText("重置PC7");
							VolumeControl.playSound();
							try {Thread.sleep(200);} catch (Exception e) {}

							AppLog.e("计价器串口检测断开，尝试复位PC7");
							MCUUtil.setIO(5, false);
							try {Thread.sleep(100);} catch (Exception e) {}
							MCUUtil.setIO(5, true);
							try {Thread.sleep(300);} catch (Exception e) {}
							try {SerialPortService.getInstance().sendSerialData6(MeterEncoder.queryMeterState());} catch (Exception e) {}

							try {Thread.sleep(2000);} catch (Exception e) {}
							c = System.currentTimeMillis()-jjqtime<2000;

							MCUUtil.reH = true;
						}
						break;
					case 4:
						try {Thread.sleep(1000);} catch (Exception e) {}

						break;
					case 5:
						try {Thread.sleep(1000);} catch (Exception e) {}
						//等dvr透传做好再判断------------------------------------------------
						c  = true;
						break;
					case 6:
						DDUtil.sendDDtime();
						try {Thread.sleep(2000);} catch (Exception e) {}
						c = System.currentTimeMillis()-ddtime<2000;
						break;
					case 7:
						try {Thread.sleep(1000);} catch (Exception e) {}
						c = chemen;
						break;
				}

				if(index==4){
					int pj3 = GPIOUtil.readIOState("/proc/input3");
					int pj5 = GPIOUtil.readIOState("/proc/input5");
					int pj6 = GPIOUtil.readIOState("/proc/input6");
					int bj = GPIOUtil.readIOState("/proc/detect_warning");
					if(!(pj3==1&&pj5==1&&pj6==1)){
						data[index] = (data[index].split("： ")[0])+"： 正常 (状态："+pj3+","+pj5+","+pj6+")"+"  (报警状态："+(bj==0?"按下":"松开)");
					}else{
						data[index] = (data[index].split("： ")[0])+"： 断开 (状态："+pj3+","+pj5+","+pj6+")"+"  (报警状态："+(bj==0?"按下":"松开)");
					}
				}else{
					if(c){
						data[index] = (data[index].split("： ")[0])+"： 正常";
					}else{
						data[index] = (data[index].split("： ")[0])+"： 断开";
					}
				}

				handler.sendMessage(handler.obtainMessage(1002));
				handler.sendMessage(handler.obtainMessage(1004, index));
			}
		}).start();


	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		isview = true;

		check(3);

//		if(DataUtil.getlastCarNum()!=null){
//			CardUtil.checkLocaInfo(DataUtil.getlastCarNum());
//		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();

		isview = false;

//		if(DataUtil.getlastCarNum()!=null){
//			CardUtil.checkLocaInfo(DataUtil.getlastCarNum());
//		}
	}

	@Override
	public void setStatus(int index, boolean status) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sendMsg(int type, Object obj) {
		// TODO Auto-generated method stub
		if(type==1012){
			handler.sendMessage(handler.obtainMessage(1001, obj));
		}
	}



}
